# -*- coding: utf-8 -*-
# @Time: 2023/4/17 10:11
# @File: commands.py
# @Desc:初始化命令文件

from models.common import Board, Banner, Post, Comment
from models.auth import User, Role, Permission
from exts import db
import random


# 初始化板块
def init_board():
    board_names = ["Python", "Flask", "Django", "爬虫"]
    for index, board_name in enumerate(board_names):
        board = Board(name=board_name, priority=len(board_names) - index)
        db.session.add(board)
    db.session.commit()
    print("板块初始化成功!")


# 初始化角色
def init_role():
    # bbs运营角色
    operator_role = Role(
        name="运营",
        desc="管理BBS论坛帖子和评论",
        permissions=Permission.POSTERS | Permission.COMMETNERS | Permission.USERS
    )
    # bbs管理员角色
    admin_role = Role(
        name="管理员",
        desc="管理整个BBS论坛网站",
        permissions=Permission.POSTERS | Permission.COMMETNERS | Permission.USERS | Permission.STAFFERS
    )
    # bbs开发者抉择
    developer_role = Role(
        name="开发者",
        desc="负责网站的开发",
        permissions=Permission.ALL_PERMISSIONS
    )
    db.session.add_all([operator_role, admin_role, developer_role])
    db.session.commit()
    print("角色添加成功")


# 对用户角色进行绑定
def bind_roles():
    user1 = User.query.filter_by(email="macleo@qq.com").first()
    user2 = User.query.filter_by(email="925143261@qq.com").first()
    user3 = User.query.filter_by(email="15088686486@qq.com").first()

    role1 = Role.query.filter_by(name="开发者").first()
    role2 = Role.query.filter_by(name="运营").first()
    role3 = Role.query.filter_by(name="管理员").first()

    user1.role = role1
    user2.role = role2
    user3.role = role3

    db.session.commit()
    print("用户和角色绑定成功！")


# 初始化开发者用户
def init_user():
    role = Role.query.filter_by(name="开发者").first()
    user = User(username='macleo', email='macleo@qq.com', password='qq12301230', is_staff=True, role=role)
    db.session.add(user)
    db.session.commit()
    print("开发者角色下用户创建成功！")


# 添加帖子测试数据
def create_test_posts():
    boards = list(Board.query.all())
    board_count = len(boards)
    for x in range(200):
        title = "我是标题%d" % x
        content = "我是内容%d" % x
        author = User.query.first()
        index = random.randint(0, board_count - 1)
        board = boards[index]
        post_model = Post(title=title, content=content, author=author, board=board)
        db.session.add(post_model)
    db.session.commit()
    print("测试帖子添加成功")
